<?php
/**
 * Created by JetBrains PhpStorm.
 * User: ncduc
 * Date: 6/15/13
 * Time: 4:39 PM
 * To change this template use File | Settings | File Templates.
 */

include_once("../libs/setup.php");
include_once("../libs/helper.php");
session_start();

if (!check_user_session()) {
    header("Location: ../signin.php");
    return;
}
assign_home_header($smarty);
$smarty->assign('wwwUrl','../');
function is_valid_research_result($id, $cur_userId, mysqli $mysqli)
{
    $query = "SELECT * FROM ket_qua_nghien_cuu WHERE Ma=$id";
    $result = $mysqli->query($query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['Ma'];
            $userId = $row['MaUser'];
            if ($userId == $cur_userId) {
                return true;
            }
        }

    }
    return false;

}

function load_research_results(mysqli $mysqli, $userId, Smarty $smarty)
{
    $query = "SELECT * FROM ket_qua_nghien_cuu WHERE MaUser=$userId";
    $result = $mysqli->query($query);
    if ($result) {
        $arr_research_results = array();
        while ($row = $result->fetch_assoc()) {
            $arr_research_results[] = array("Ma" => $row["Ma"],
                "TenSanPham" => $row["TenSanPham"],
                "TenTacGia" => $row["TenTacGia"],
                "TenTapChi" => $row["TenTapChi"],
                "MaLoaiKQNghienCuu" => $row["MaLoaiKQNghienCuu"],
                "ISSN" => $row["ISSN"],
                "MinhChung" => $row["MinhChung"],
                "GhiChu" => $row["GhiChu"]
            );
        }
    }
    if ($mysqli->error) {
        system_failed($mysqli->error, $smarty);
        $mysqli->close();
        return false;
    }
    $smarty->assign('research_results', $arr_research_results);
    return true;
}

function load_research_result(mysqli $mysqli, $id, Smarty $smarty)
{
    $query = "SELECT * FROM ket_qua_nghien_cuu WHERE Ma=$id";
    $result = $mysqli->query($query);
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $id = $row['Ma'];
            $product_name = $row['TenSanPham'];
            $author = $row['TenTacGia'];
            $publisher = $row['TenTapChi'];
            $research_type = $row['MaLoaiKQNghienCuu'];
            $issn = $row['ISSN'];
            $evidence_uploaded = $row['MinhChung'];
            $note = $row['GhiChu'];
            $smarty->assign('id', $id);
            $smarty->assign('product_name', $product_name);
            $smarty->assign('author', $author);
            $smarty->assign('publisher', $publisher);
            $smarty->assign('research_type', $research_type);
            $smarty->assign('issn', $issn);
            $smarty->assign('evidence_uploaded', $evidence_uploaded);
            $smarty->assign('note', $note);
        }
    }
    if ($mysqli->error) {
        system_failed($mysqli->error, $smarty);
        $mysqli->close();
        return false;
    }

    return true;
}

function add_research_result(mysqli $mysqli, array $result_info, Smarty $smarty)
{
    $sql = "INSERT INTO ket_qua_nghien_cuu(MaUser, TenSanPham, TenTacGia, TenTapChi,MaLoaiKQNghienCuu,ISSN,GhiChu)
    VALUES({$result_info['user_id']},'{$result_info['product_name']}','{$result_info['author']}','{$result_info['publisher']}','{$result_info['research_type']}','{$result_info['issn']}','{$result_info['note']}')";
    $result = $mysqli->query($sql);
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $sql, $smarty);
        $mysqli->close();
        return false;
    }
    return true;
}

function save_research_result(mysqli $mysqli, array $result_info, Smarty $smarty)
{
    $sql = "UPDATE ket_qua_nghien_cuu SET TenSanPham='{$result_info['product_name']}', TenTacGia='{$result_info['author']}', TenTapChi='{$result_info['publisher']}',MaLoaiKQNghienCuu={$result_info['research_type']}, ISSN='{$result_info['issn']}',GhiChu='{$result_info['note']}' WHERE Ma={$result_info['id']}";
    $result = $mysqli->query($sql);
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $sql, $smarty);
        $mysqli->close();
        return false;
    }
    return true;
}

function save_upload_evidence(mysqli $mysqli, array $result_info, Smarty $smarty)
{
    $upload_result = upload_file('evidence_upload', $result_info['user_id']);
    if (strlen($upload_result) > 0) //upload file error
    {
        $message = $upload_result;
        $smarty->assign('is_display', "block");
        $smarty->assign('message', $message);
    } else {
        $filename = $_FILES['evidence_upload']['name'];
        $sql = "UPDATE ket_qua_nghien_cuu SET MinhChung = '{$filename}' WHERE Ma = {$result_info['id']}";
        $result = $mysqli->query($sql);
        if ($mysqli->error) {
            system_failed($mysqli->error . "sql: " . $sql, $smarty);
            $mysqli->close();
            return false;
        }
    }
    return true;
}

function delete_research_result(mysqli $mysqli, $id, Smarty $smarty)
{
    $sql = "DELETE FROM ket_qua_nghien_cuu WHERE Ma=$id";

    $result = $mysqli->query($sql);
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $sql, $smarty);
        $mysqli->close();
        return false;
    }
    return true;
}

function get_research_result_from_page()
{
    $result_info = array(
        'id' => addslashes($_REQUEST['id']),
        'user_id' => addslashes($_SESSION['ma_user']),
        'product_name' => addslashes($_REQUEST['product_name']),
        'author' => addslashes($_REQUEST['author']),
        'publisher' => addslashes($_REQUEST['publisher']),
        'research_type' => addslashes($_REQUEST['research_type']),
        'issn' => addslashes($_REQUEST['issn']),
        'note' => addslashes($_REQUEST['note'])
    );
    return $result_info;
}
function load_research_types(mysqli $mysqli, Smarty $smarty)
{
    $query = "select * from loai_ket_qua_nghien_cuu";
    $result = $mysqli->query($query);
    if($result)
    {
        $research_types = array();
        while ($row = $result->fetch_assoc())
        {
            $research_types[] = array(
                'Ma' => $row['Ma'],
                'LoaiKetQuaNghienCuu' => $row['LoaiKetQuaNghienCuu']
            );
        }

        $smarty->assign('research_type_array',$research_types);
    }
    if ($mysqli->error) {
        system_failed($mysqli->error . "sql: " . $query, $smarty);
        $mysqli->close();
        return false;
    }
    return true;

}
$mysqli = connect_database($smarty);
$cur_userId = $_SESSION['ma_user'];
if (empty($_REQUEST['save']) && empty($_REQUEST['next'])) {
    if (!empty($_REQUEST['id']) && !empty($_REQUEST['action'])) {

        if (!is_valid_research_result($_REQUEST['id'], $cur_userId, $mysqli)) {
            $message = "Không tìm thấy kết quả nghiên cứu";
            $smarty->assign('is_display', "block");
            $smarty->assign('message', $message);
        } else {
            if ($_REQUEST['action'] == "edit") {
                //$result_info = get_research_result_from_page();

                if(!load_research_result($mysqli,$_REQUEST['id'],$smarty))
                {
                    return;
                }


            }
            if ($_REQUEST['action'] == "delete") {

                if (!delete_research_result($mysqli, $_REQUEST['id'], $smarty)) {
                    return;
                }
                $message = "Đã xóa thành công kết quả nghiên cứu";
                $smarty->assign('is_display', "block");
                $smarty->assign('type_message','success');
                $smarty->assign('message', $message);
            }

        }
    }else
    {
        $smarty->assign('id',null);
    }

} else {
    if (!empty($_REQUEST['save'])) {
        $activity = get_research_result_from_page();
        if(empty($activity['id']))
        {
            if(!add_research_result($mysqli,$activity,$smarty))
            {
                return;
            }
            $message = "Thêm thành công kết quả nghiên cứu mới";
            $smarty->assign('is_display', "block");
            $smarty->assign('type_message','success');
            $smarty->assign('message', $message);
            $activity['id'] = $mysqli->insert_id;

        }
        else
        {
            if(!save_research_result($mysqli,$activity,$smarty))
            {
                return;
            }
            $message = "Đã sửa thành công kết quả nghiên cứu";
            $smarty->assign('is_display', "block");
            $smarty->assign('type_message','success');
            $smarty->assign('message', $message);
        }

        if($_FILES['evidence_upload']['size']>0)
        {
            if(!save_upload_evidence($mysqli,$activity,$smarty))
                return;

        }
    } else {
        header("Location: 4.php");
    }
}
//load data table
if(!load_research_results($mysqli,$cur_userId,$smarty))
    return;
if(!load_research_types($mysqli,$smarty))
    return;
$smarty->display('profile/4_2.tpl');